import React from "react";
import {NavBar, List, Button, Toast} from 'antd-mobile'
import './UserCenter.less';
import axios from 'axios';
export default function UserCenter(props) {

    //声明状态
    const [user, setUser] = React.useState({});
    
    //钩子函数 componentDidMount
    React.useEffect( () => {
        async function fn(){
            //发送请求获取用户的数据
            let result = await axios.post('/login/verify');
            //判断
            if(result.data.code !== 20000){
                Toast.show({
                    icon: 'fail',
                    content: '您还没有登录, 请先登录!',
                })
                //没有登录跳转到 登录页面
                props.history.push('/login');
            }else{
                //使用数据渲染组件
                setUser(result.data.data);
            }
        }
        fn();
        
    }, []);

    //退出登录
    const logout =async () => {
        //发送请求
        let result = await axios.post('/logout', {_id: user._id});
        if(result.data.code !== 20000){
            Toast.show({
                icon: 'fail',
                content: '退出失败',
            });
        }else{
            // 
            Toast.show({
                icon: 'success',
                content: '成功退出',
            });
            //跳转
            props.history.replace('/login');
        }
    }

    return (
        <div className="user-container">
            <NavBar back={null}>
                个人中心
            </NavBar>

            {/* 图片部分 start */}
            <div className="profile">
                <img src={user.avatar} alt="" />
                <div className="h-5"></div>
                <p>欢迎用户 {user.username}</p>
            </div>
            {/* 图片部分 end */}

            {/* 个人信息 start */}
            <div className="info">
            <List header='个人信息'>
                <List.Item> <span>昵称</span> <span>{user.nickName}</span> </List.Item>
                <List.Item> <span>手机</span> <span>{user.phone}</span> </List.Item>
            </List>
            </div>
            {/* 个人信息 end */}

            <div className="h-20"></div>
            <div className="h-10"></div>
            <div className="h-20"></div>
            <Button block size="middle" color="danger" onClick={logout}>退出登录</Button>
        
        </div>
    );
}
